<template>
    <!-- 根据项目选择对应人员 -->
    <a-select
        :allowClear="allowClear"
        :showSearch="showSearch"
        :optionFilterProp="optionFilterProp"
        filterOption
        v-bind="$attrs"
        v-on="$listeners"
        v-model="localValue"
        :placeholder="placeholder"
    >
        <a-select-option  v-for="item in personList" :key="item.employeeId" :value="item.employeeId" :title="noRepeat?item.postNme:''">
            {{ item.employeeName }}
    </a-select-option>
    </a-select>
</template>

<script>
import { getOrganizePeopleList, getOneOrgUsers, getOrgEmployeesListBy } from '@/api/commons.js'
import { getStaffAll } from '@/api/subassembly/TreeSelectOrganization'
export default {
    model: {
        event: 'packageChange'
    },
    props: {
        valueKey: {
          type: String,
          default: 'userId'
        },
        allowClear: {
            type: Boolean,
            default: true
        },
        showSearch: {
            type: Boolean,
            default: true
        },
        optionFilterProp: {
            type: String,
            default: 'children'
        },
        placeholder: {
            type: String,
            default: '请选择'
        },
        // 项目ID
        projectId: {
            type: [String, Number],
            default: ''
        },

        // 组织ID根据组织ID查人
        orgId: {
            type: [String, Number],
            default: ''
        },
        //是否请求项目部下面的人
        isProject: {
            type: Boolean,
            default: () => true
        },
        // 双向绑定使用
        value: {
            type: [String, Number, Object, Array]
        },
        // 是否过滤重复的人员
        needFilterDuplicate: {
            type: Boolean,
            default: true
        },
        //如果是编辑，第一次不要重置绑定的值。。。。
        isEdit: {
            type: Boolean,
            default: () => true
        },
        // 筛选参数：0 在岗；1 更换中；2 移除中；3 新增中
        statusCode: {
            type: String,
            default: () => ''
        },
        isOrg: {
            type: Boolean,
            default: false
        },
        addPhone: {
            type: Boolean,
            default: true
        },
        addJob: {
            type: Boolean,
            default: false
        },
        getIdcard: {
            type: Boolean,
            default: false
        },
        // 是否继续防止项目id不存在报错
        isContinue:{
            type: Boolean,
            default: true
        },
        isShowUnit: {
            type: Boolean,
            default: true 
        },
        //是否去重，同一人岗位不同
        noRepeat:{
            type: Boolean,
            default: false  
        },
        // 如果isOrg 为true 并且不需要重复请求时 可以手动传入用户列表
        userList: {
            type: Array,
            default() {
                return []
            }
        },
        //不需要重复请求 配合userList， isOrg 使用
        noRepeatRequest: {
            type: Boolean,
            default: false
        }
    },
    mounted() {
        this.getPersonList()
        //console.log(2)
        if (this.$attrs.mode == 'multiple') {
            this.isMultiple = true
        }
    },
    watch: {
        projectId: {
            handler() {
                if (this.isEdit) {
                    if (this.isCanClear) {
                        this.localValue = void 0
                    } else {
                        if (this.projectId) {
                            this.isCanClear = true
                        }
                    }
                } else {
                    this.localValue = void 0
                }
                this.$emit('resetSelf')
                this.getPersonList()
            }
        },
        orgId: {
            handler() {
                if (this.isEdit) {
                    if (this.isCanClear) {
                        this.localValue = void 0
                        this.$emit('resetSelf')
                    } else {
                        if (this.orgId) {
                            this.isCanClear = true
                        }
                    }
                } else {
                    this.localValue = void 0
                    this.$emit('resetSelf')
                }

                this.getPersonList()
            }
        },
        userList() {
            console.log(1)
            this.getPersonList()
        }
    },
    computed: {
        localValue: {
            get() {
                if (this.personList.length > 0) {
                    this.$emit(
                        'update:option',
                        this.personList?.find((item) => item.userId === this.value)
                    )
                    this.$emit(
                        'getOption',
                        this.personList.find((item) => item.userId === this.value)
                    )
                }
                let currentLabel
                let target = this.personList.find((item) => item.employeeId === this.value || item.userId === this.value)
                currentLabel = target && target.employeeName
                if (this.isMultiple) {
                    target =
                        this.personList.filter((item, index) => {
                            return this.value?.includes(item.employeeId || item.userId)
                        }) || []
                    currentLabel = target.length && target.map((v) => v.employeeName)
                }
                this.$emit('update:currentLabel', currentLabel || '')
                this.$emit('personChanged', target || {})
                let noVal = this.isMultiple ? [] : void 0
                return this.value || noVal
            },
            set(val) {
                this.$emit('packageChange', val)
                let currentLabel
                let target = this.personList.find((item) => item.employeeId === val || item.userId === this.value)
                currentLabel = target && target.employeeName
                if (this.isMultiple) {
                    target =
                        this.personList.filter((item, index) => {
                            return this.value?.includes(item.employeeId || item.userId)
                        }) || []
                    currentLabel = target.length && target.map((v) => v.employeeName)
                }
                this.$emit('update:currentLabel', currentLabel || '')
                this.$emit('personChanged', target || {})
            }
        }
    },
    data() {
        return {
            isCanClear: !this.isEdit, // 是否清除
            personList: [],
            isMultiple: false
        }
    },
    methods: {
     removeDuplicateObj(arr){ //去重加岗位拼接
       let obj = {},
       newArr = [];
        arr.forEach(v=>{
        if (obj.hasOwnProperty(v.employeeId)) {  
        obj[v.employeeId].push(v.jobName)
        } else{
         obj [v.employeeId] = [v.jobName]
         newArr.push(v)
    }
     })
      let keys = Object.keys(obj);
      if(keys && keys.length && newArr && newArr.length){
        keys.map((item)=>{
            newArr.map((iCitem)=>{
                if(item == iCitem.employeeId){
                    iCitem.postNme = obj[item]?.join('/')
                }
            })
        })
      }
        return newArr
      },
        /**
         * 获取指定id的对象
         */
        getPersonObj(id) {
            const target = this.departments.find((item) => item.employeeId === id)
            return (target && target) || void 0
        },
        async getPersonList() {
            if (!this.isContinue || (!this.projectId && !this.orgId && !this.noRepeatRequest) ) return
            try {
                const params = {
                    id: this.projectId,
                    detail: this.getIdcard
                }
                let res = {}
              //  console.log(this.isOrg)
                if (this.isOrg) {
                    if(this.noRepeatRequest) {
                        res = this.userList
                    } else {
                        res = await getOneOrgUsers({ pageNumber: 1, pageSize: 999999, rootOrgId: this.orgId })
                    }
                } else if (this.isProject) {
                    res = await getOrganizePeopleList(params);
                    if(this.noRepeat && res.data && res.data.length){
                        res.data = this.removeDuplicateObj(res.data);
                    }
                } else {
                    res = await getStaffAll({ rootOrgId: this.orgId })

                    res.data.forEach((item) => {
                        item.employeeId = item.id
                        if (this.addPhone) {
                            item.employeeName = this.isShowUnit ? (item.name + ' ' + item.phone) : item.name
                        }
                    })
                }

                let list = res.data || []
                if (this.isOrg) {
                    let arr = ((res.data && res.data.list) || [])
                    if(this.noRepeatRequest) {
                        arr = res;
                    }
                    list = arr.map((item) => {
                        item.employeeId = item[this.valueKey]
                        item.employeeName = item.name
                        if (this.addJob) {
                            item.employeeName = this.isShowUnit ? (item.name + ' ' + item.postPNames.toString()) : item.name
                        }
                        if (this.addPhone) {
                            item.employeeName = this.isShowUnit ? (item.name + ' ' + item.phone) : item.name
                        }
                        return item
                    })
                } else if (this.isProject) {
                    list = res.data.map((item) => {
                        if (item.employeeName.indexOf('(') != -1) {
                            item.employeeName = item.employeeName.substring(0, item.employeeName.indexOf('('))
                        }

                        if(!this.noRepeat){
                            item.employeeName = this.isShowUnit ? (item.employeeName + ' ' + item.jobName) : item.employeeName
                        }

                        return item
                    })
                }
                if (this.needFilterDuplicate) {
                    const map = new Map()
                    list = list.filter((item) => {
                        if (map.get(item.employeeId)) {
                            return false
                        } else {
                            map.set(item.employeeId, true)
                            return true
                        }
                    })
                    map.clear()
                }
                // 筛选特殊状态人员
                if (this.statusCode != '') {
                    list = list.filter((item) => item.statusCode == this.statusCode)
                }
                this.personList = list
                this.$emit('update:list', this.personList)
            } catch {
                this.personList = []
            }
        }
    }
}
</script>

<style>
</style>